package com.example.ccj.b.c.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.ccj.R;
import com.example.ccj.b.c.draw.DrawFenShuView;
import com.example.ccj.b.c.draw.FenShu;
import com.example.ccj.b.c.draw.VerticalImageSpan;
import com.example.ccj.u.AdaptScreenUtils;
import com.example.ccj.u.GsonUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 加载题干
 * 目前包含加载分数以及填空题
 * 注意：填空题的空要以()代表，分数题要是FenShu类转换JSON后的数据且该数据使用"&///"作为前缀，"///&"作为后缀
 * 开始先设置文本setMText() 设置后自动解析填空题的空以及分数
 * 在填空题填入数据后可调用setTianKongText(String str,int index)方法写入数据
 *
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/6/1 15:22
 */
public class MTextView extends androidx.appcompat.widget.AppCompatTextView implements View.OnClickListener{

    long clickTime = 0;
    int checkInterval;
    boolean onlyOne;
    OnClickListener onClickListenerN;

    public void setOnClickListener(@Nullable OnClickListener onClickListenerN) {
        this.onClickListenerN = onClickListenerN;
    }

    @Override
    public void onClick(View v) {
        if (onlyOne) {
            if (onClickListenerN != null) onClickListenerN.onClick(v);
            this.setEnabled(false);
        } else if (!(System.currentTimeMillis() - clickTime < checkInterval)) {
            clickTime = System.currentTimeMillis();
            if (onClickListenerN != null) onClickListenerN.onClick(v);
        }
    }

    public MTextView(@NonNull Context context) {
        super(context);
        readableText = new StringBuilder();
        super.setOnClickListener(this);
    }

    public MTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MTextView);
        //点击间隔
        checkInterval = typedArray.getInteger(R.styleable.MTextView_m_text_click_interval, 500);
        onlyOne = typedArray.getBoolean(R.styleable.MTextView_m_text_only_one, false);

        super.setOnClickListener(this);
        //回收
        typedArray.recycle();
        readableText = new StringBuilder();
    }

    public void setPaddingForDp(int left, int top, int right, int bottom) {
        setPadding(AdaptScreenUtils.pt2Px(left),
                AdaptScreenUtils.pt2Px(top),
                AdaptScreenUtils.pt2Px(right),
                AdaptScreenUtils.pt2Px(bottom));
    }

    //需要转换的文本
    String text = "";
    //分数文本前缀
    String fenShuPrefixChar = "&///";
    //分数文本后缀
    String fenShuSuffixChar = "///&";
    //填空题的空分割符号
    String tianKongReplaceChar = "\\(\\)";
    //分数比原文本大的系数
    float overflowCoefficient = 0.5f;
    //分数是否缩放
    boolean fenShuIsOverflow = true;
    //填空题分割后的文本
    String[] tianKong;
    //填空题填入的文本颜色
    int tianKongTextColor = Color.BLUE;
    //填空题空的数量
    int tianKongNum = 0;
    //文本类型
    int type = -1;

    boolean drawFenShuResult = false;


    public void setFenShuIsOverflow(boolean fenShuIsOverflow) {
        this.fenShuIsOverflow = fenShuIsOverflow;
    }

    //记录每个填空题的空的开始结束位置，用于改变其颜色
    //key代表那个空，下标0开始，value 中第一个数据代表开始位置，第二个数据代表结束位置
    Map<Integer, Pair<Integer,Integer>> tianKongIndex = new HashMap<>();

    /**
     * 设置默认文本
     * @param text 文本
     * @param type 开头类型 0：答案 其他看getTypeText(type)类中定义
     */
    public void setMText(CharSequence text ,int type) {
        this.type = type;
        this.text = getTypeText(type) + text.toString();
        tianKong = this.text.split(tianKongReplaceChar);
        tianKongNum = tianKong.length-1;
        this.text = this.text.replaceAll(tianKongReplaceChar,"(   )");
        handleText(this.text);
    }

    /**
     * 设置默认文本
     * @param text 文本
     */
    public void setMText(CharSequence text) {
        this.text = text.toString();
        tianKong = this.text.split(tianKongReplaceChar);
        tianKongNum = tianKong.length-1;
        this.text = this.text.replaceAll(tianKongReplaceChar,"(   )");
        handleText(this.text);
    }

    /**
     * 设置默认文本
     * @param text 文本
     * @param drawFenShuResult 是否绘制分数结果符号
     */
    public void setMText(CharSequence text,boolean drawFenShuResult) {
        this.text = text.toString();
        tianKong = this.text.split(tianKongReplaceChar);
        tianKongNum = tianKong.length-1;
        this.text = this.text.replaceAll(tianKongReplaceChar,"(   )");
        this.drawFenShuResult = drawFenShuResult;
        handleText(this.text);
    }

    List<Pair<Integer,Integer>> fenShuResult;

    /**
     * 设置默认文本
     * @param text 文本
     * @param fenShuResult 每个分数试题的结果
     */
    public void setMText(CharSequence text , List<Pair<Integer,Integer>> fenShuResult) {
        this.text = text.toString();
        tianKong = this.text.split(tianKongReplaceChar);
        tianKongNum = tianKong.length-1;
        this.text = this.text.replaceAll(tianKongReplaceChar,"(   )");
        this.drawFenShuResult = true;
        this.fenShuResult = fenShuResult;
        handleText(this.text);
    }

    private final StringBuilder readableText;

    /**
     * 设置填空题文本
     *
     * @param str 文本
     * @param index 要修改文字的文本位置 ，可根据getTianKongNum()方法获取空的数量，根据此数量生成相应的文本输入框，并设置文本监听进行回写文本
     */
    public void setTianKongText(String str,int index){
        //填空文本加载
        StringBuilder builder = new StringBuilder();
        int start = 0;
        if (tianKong.length > index) {
            for (int i = 0; i < tianKong.length-1; i++) {
                start = start + tianKong[i].length()+1;
                if (index == i) {
                    if (StringUtils.isEmpty(str)) {
                        builder.append(tianKong[i]).append("(   )");
                    } else {
                        tianKongIndex.put(i,new Pair<>(start,start+str.length()));
                        builder.append(tianKong[i]).append("(").append(str).append(")");
                    }
                }
//                else {
//                    builder.append(tianKong[i]).append("(   )");
//                }
            }
            builder.append(tianKong[tianKong.length-1]);
        }
        text = builder.toString();
        //其他类型文本加载
        handleText(builder.toString());
    }

    @Override
    public void setTextSize(float size) {
        super.setTextSize(size);
        handleText(text);
    }

    /**
     * 获取纯文本，用于语音合成
     * @return
     */
    public String getPureText(){

        StringBuilder stringBuilder = new StringBuilder(text);

        //处理填空
        for (Integer i : tianKongIndex.keySet()) {
            Pair<Integer, Integer> integerIntegerPair = tianKongIndex.get(i);
            if (integerIntegerPair!=null) {
                stringBuilder.replace(integerIntegerPair.first-1,integerIntegerPair.first," ");
                stringBuilder.replace(integerIntegerPair.second,integerIntegerPair.second+1," ");
            }
        }

        //处理分数
        if (stringBuilder.toString().contains(fenShuPrefixChar)) {
            String[] fenShuSplit = stringBuilder.toString().split(fenShuPrefixChar);
            for (String s : fenShuSplit) {
                String[] split = s.split(fenShuSuffixChar);
                if (split.length >= 2) {
                    List<FenShu> fenShus = GsonUtils.fromJsonList(split[0], FenShu.class);
                    for (int i = 0; i < fenShus.size(); i++) {
                        readableText.append(fenShus.get(i).fenMu).append("分之").append(fenShus.get(i).fenZi);
                        if (i < fenShus.size() -1 )  {
                            if (fenShus.get(i).isJiaFa) readableText.append("加");
                            else readableText.append("减");
                        }
                    }
                    readableText.append(split[1]);
                } else {
                    readableText.append(s);
                }
            }
        } else {
            readableText.append(stringBuilder);
        }
        return readableText.toString();
    }


    /**
     * 核心功能 处理文本
     * @param content 文本
     */
    private void handleText(String content){
        final float textSize = getTextSize();
        SpannableString spannableString = new SpannableString(content);

        //处理试题类型
        if (type >= 0) {
            BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.parseColor("#6BFFF1"));
            spannableString.setSpan(backgroundColorSpan,0,4,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
            spannableString.setSpan(styleSpan,1,3,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        //处理分数
        int index = 0;
        if (content.contains(fenShuPrefixChar)) {
            String[] fenShu = content.split(fenShuPrefixChar);
            //起始遍历位置
            int startIndex = 0;
            //文本如果不是以分数开头的
            if (!content.startsWith(fenShuPrefixChar)) {
                index = fenShu[0].length();
                startIndex = 1;
            }

            //遍历随后的分数以及文本
            for (int i = startIndex; i < fenShu.length; i++) {
                if (StringUtils.isEmpty(fenShu[i])) continue;
                //分割出文本和分数
                String[] fs = fenShu[i].split(fenShuSuffixChar);
                if (fs.length > 0) {
                    //获取分数位图
                    List<FenShu> fenShus = GsonUtils.fromJsonList(fs[0], FenShu.class);
                    DrawFenShuView drawFenShuView = new DrawFenShuView(getContext(),fenShus.toArray(new FenShu[0]),(int)textSize,drawFenShuResult);
                    //画分数结果
                    if (drawFenShuResult) {
                        if (fenShuResult != null && fenShuResult.size() > i) {
                            Pair<Integer, Integer> integerIntegerPair = fenShuResult.get(i);
                            drawFenShuView.setResultFenZi(integerIntegerPair.first);
                            drawFenShuView.setResultFenMu(integerIntegerPair.second);
                        }
                    }
                    Bitmap bitmap = drawFenShuView.getBitmap();
                    Bitmap scaleBitmap;
                    if (fenShuIsOverflow) {
                        //获取位图缩放比例
                        int height = bitmap.getHeight();
                        //位图缩放系数计算公式（（文本大小+文本大小*缩放后与文本的比例）/原文本高度）
                        float scaleHeight = (textSize + textSize * overflowCoefficient) / height;
                        //图片等比例缩放
                        scaleBitmap = ImageUtils.scale(bitmap,scaleHeight,false) ;
                    } else {
                        scaleBitmap = bitmap;
                    }

                    VerticalImageSpan imageSpan;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        imageSpan = new VerticalImageSpan(getContext(), scaleBitmap, VerticalImageSpan.ALIGN_CENTER);
                    } else {
                        imageSpan = new VerticalImageSpan(getContext(), scaleBitmap);
                    }
                    //结束位置
                    int e = index+fs[0].length() + fenShuPrefixChar.length()+ fenShuSuffixChar.length();

                    spannableString.setSpan(imageSpan, index, e, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    if (fs.length > 1) index = e + fs[1].length();


                }
            }
        }

        //填空题的空设置文本颜色及下划线
        for (Integer key: tianKongIndex.keySet()) {
            Pair<Integer, Integer> integerIntegerPair = tianKongIndex.get(key);
            if (integerIntegerPair != null) {
                //设置文本颜色
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(tianKongTextColor);
                spannableString.setSpan(foregroundColorSpan,integerIntegerPair.first,integerIntegerPair.second,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置文本的下划线
                UnderlineSpan underlineSpan = new UnderlineSpan();
                spannableString.setSpan(underlineSpan,integerIntegerPair.first,integerIntegerPair.second,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        setText(spannableString);
    }

    private String getTypeText(int type){
        if (type == 0) return " 答案 ";
        if (type == 1) return " 单选 ";
        if (type == 2) return " 多选 ";
        if (type == 3) return " 判断 ";
        if (type == 4 || type == 5) return " 填空 ";
        if (type == 6) return " 问答 ";
        if (type == 7) return " 翻译 ";
        return "";
    }


    public void setFenShuPrefixChar(String fenShuPrefixChar) {
        this.fenShuPrefixChar = fenShuPrefixChar;
    }

    public void setFenShuSuffixChar(String fenShuSuffixChar) {
        this.fenShuSuffixChar = fenShuSuffixChar;
    }

    public void setTianKongReplaceChar(String tianKongReplaceChar) {
        this.tianKongReplaceChar = tianKongReplaceChar;
    }

    public void setOverflowCoefficient(float overflowCoefficient) {
        this.overflowCoefficient = overflowCoefficient;
    }

    public void setTianKongTextColor(int tianKongTextColor) {
        this.tianKongTextColor = tianKongTextColor;
    }

    public String getMText() {
        return text;
    }

    public String getFenShuPrefixChar() {
        return fenShuPrefixChar;
    }

    public String getFenShuSuffixChar() {
        return fenShuSuffixChar;
    }

    public String getTianKongReplaceChar() {
        return tianKongReplaceChar;
    }

    public float getOverflowCoefficient() {
        return overflowCoefficient;
    }

    public String[] getTianKong() {
        return tianKong;
    }

    public int getTianKongTextColor() {
        return tianKongTextColor;
    }

    public int getTianKongNum() {
        return tianKongNum;
    }

    public Map<Integer, Pair<Integer, Integer>> getTianKongIndex() {
        return tianKongIndex;
    }



    public long getClickTime() {
        return clickTime;
    }

    public void setClickTime(long clickTime) {
        this.clickTime = clickTime;
    }

    public int getCheckInterval() {
        return checkInterval;
    }

    public void setCheckInterval(int checkInterval) {
        this.checkInterval = checkInterval;
    }

    public boolean isOnlyOne() {
        return onlyOne;
    }

    public void setOnlyOne(boolean onlyOne) {
        this.onlyOne = onlyOne;
    }
}